﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using IBatisNet.DataMapper;
using StateGrid.OperationLog;
using StateGrid;
using System.Xml;
using StateGrid.GlobalVariables;

namespace StateGrid.GYBG
{
    /// <summary>
    /// Summary description for GYBG_DAO
    /// </summary>
    public class GYBG_DAO
    {
        private ISqlMapper sqlMapper = Mapper.Instance();

        /// <summary>
        /// 日志操作对象
        /// </summary>
        private OperationLog_DAO operationLogDAO = new OperationLog_DAO();

        /// <summary>
        /// 获取所有国研报告分类
        /// </summary>
        /// <returns></returns>
        public IList<GYBG_FL> GetAllGYBG_FL()
        {
            return sqlMapper.QueryForList<GYBG_FL>("SelectAllGYBG_FL", null);
        }

        /// <summary>
        /// 获取所有国研报告篇名信息
        /// </summary>
        /// <returns></returns>
        public IList<GYBG_PM> GetAllGYBG_PM()
        {
            return sqlMapper.QueryForList<GYBG_PM>("SelectAllGYBG_PM", null);
        }

        /// <summary>
        /// 按分类编码查找分类信息
        /// </summary>
        /// <param name="flbm"></param>
        /// <returns></returns>
        public GYBG_FL GetGYBG_FLByFlbm(String flbm)
        {
            return sqlMapper.QueryForObject<GYBG_FL>("SelectGYBG_FLByFlbm", flbm);
        }

        /// <summary>
        /// 按分类编码查找分类信息
        /// </summary>
        /// <param name="flmc">分类名称</param>
        /// <returns></returns>
        public GYBG_FL GetGYBG_FLByFlmc(String flmc)
        {
            return sqlMapper.QueryForObject<GYBG_FL>("SelectGYBG_FLByFlmc", flmc);
        }

        /// <summary>
        /// 获取指定索引编码、年份、期号的片名数量
        /// </summary>
        /// <param name="sybm">分类编码</param>
        /// <param name="nf">年份</param>
        /// <param name="qh">期号</param>
        /// <returns></returns>
        public int GetCountSomeGYBG_PM(String flbm,String nf,String qh)
        {
            IDictionary<String, Object> para = new Dictionary<String, Object>();

            String wjm=null;

            if (null == flbm || "".Equals(flbm))
            {
            }
            else
            {
                wjm = flbm;
                if (null!=nf&&nf.Length==4)
                {
                    wjm += '-' + nf;
                    if (null != qh && qh.Length == 2)
                    {
                        wjm += '-' + qh;
                    }
                }
            }

            if (null != wjm)
            {
                wjm += '%';
            }

            para.Add("wjm", wjm);
            return sqlMapper.QueryForObject<int>("CountSomeGYBG_PM", para);
        }


        /// <summary>
        /// 获取指定索引编码、年份、期号的片名数量
        /// </summary>
        /// <param name="sybm">索引编码</param>
        /// <param name="nf">年份</param>
        /// <param name="qh">期号</param>
        /// <param name="start">起始位置</param>
        /// <param name="end">结束位置</param>
        /// <returns></returns>
        public IList<GYBG_PM> GetSomeGYBG_PM(String sybm,String nf,String qh,int start,int end)
        {
            IDictionary<String, Object> para = new Dictionary<String, Object>();

            String wjm=null;

            if (null == sybm || "".Equals(sybm))
            {
            }
            else
            {
                wjm = sybm;
                if (null!=nf&&nf.Length==4)
                {
                    wjm += '-' + nf;
                    if (null != qh && qh.Length == 2)
                    {
                        wjm += '-' + qh;
                    }
                }
            }

            if (null != wjm)
            {
                wjm += '%';
            }

            para.Add("wjm", wjm);
            para.Add("start", start);
            para.Add("end", end);
            return sqlMapper.QueryForList<GYBG_PM>("SelectSomeGYBG_PM", para);
        }

        /// <summary>
        /// 获取指定文件名的篇名信息
        /// </summary>
        /// <param name="wjm">文件名</param>
        /// <returns></returns>
        public GYBG_PM GetGYBG_PMByWjm(String wjm)
        {
            return sqlMapper.QueryForObject<GYBG_PM>("SelectGYBG_PMByWjm", wjm);
        }

        /// <summary>
        /// 插入一条分类信息
        /// </summary>
        /// <param name="gybg_fl">分类信息</param>
        /// <returns></returns>
        public Boolean InsertGYBG_FL(GYBG_FL gybg_fl)
        {
            Boolean flag = true;
            try
            {
                sqlMapper.Insert("InsertGYBG_FL", gybg_fl);
            }
            catch (Exception)
            {
                flag = false;
            }
            return flag;
        }

        /// <summary>
        /// 插入一条篇名信息
        /// </summary>
        /// <param name="gybg_pm">篇名信息</param>
        /// <returns></returns>
        public Boolean InsertGYBG_PM(GYBG_PM gybg_pm)
        {
            Boolean flag = true;
            OperationLogItem operationLog = this.GetOperationLogItem(gybg_pm, "INSERT", null);
            try
            {
                sqlMapper.Insert("InsertGYBG_PM", gybg_pm);
                this.operationLogDAO.insertLogItem(operationLog);
            }
            catch (Exception)
            {
                flag = false;
            }
            return flag;
        }

        /// <summary>
        /// 更新一条分类信息
        /// </summary>
        /// <param name="gybg_fl">要更新的分类信息</param>
        /// <returns></returns>
        public Boolean UpdateGYBG_FL(GYBG_FL gybg_fl)
        {
            Boolean flag = true;
            int back = sqlMapper.Update("UpdateGYBG_FL", gybg_fl);
            if (back <= 0)
            {
                flag = false;
            }
            return flag;

        }
        /// <summary>
        /// 更新一条篇名信息
        /// </summary>
        /// <param name="gybg_pm">要更新的篇名信息</param>
        /// <param name="uname">操作用户名</param>
        /// <returns></returns>
        public Boolean UpdateGYBG_PM(GYBG_PM gybg_pm, String uname)
        {
            Boolean flag = true;
            int back=sqlMapper.Update("UpdateGYBG_PM", gybg_pm);
            if (back <= 0)
            {
                flag = false;
            }
            if (flag)
            {
                OperationLogItem operationLog = this.GetOperationLogItem(gybg_pm, "UPDATE", uname);
                this.operationLogDAO.insertLogItem(operationLog);
            }
            return flag;
        }

        /// <summary>
        /// 按文件名删除篇名信息
        /// </summary>
        /// <param name="wjm">文件名</param>
        /// <returns></returns>
        public Boolean DeleteGYBG_FL(String flbm)
        {
            Boolean flag = true;
            int back = sqlMapper.Delete("DeleteGYBG_FLByFlbm", flbm);
            if (back <= 0)
            {
                flag = false;
            }
            return flag;
        }

        /// <summary>
        /// 按文件名删除篇名信息
        /// </summary>
        /// <param name="wjm">文件名</param>
        /// <param name="uname">操作用户名</param>
        /// <returns></returns>
        
        public int DeleteGYBG_PM(String wjm,String uname)
        {
            int result = 0;

            GYBG_PM gybgPM = this.GetGYBG_PMByWjm(wjm);

            OperationLogItem operationLog = null;


            //切分文件名
            String[] str = wjm.Split('-');
            if (str.Length < 4)
            {
                return result;
            }
            //文件名前缀
            String wjmStr = str[0] + "-" + str[1] + "-" + str[2] + "-";

            //目录文件名
            String startWjm = wjmStr + "0000.PDF";
            String dwjm = wjm.Replace(".PDF", ".DOC");
            //删除指定篇名及文件
            if (OperationFile.DeleteFile(wjm)&&OperationFile.DeleteFile(dwjm))
            {
                result = sqlMapper.Delete("DeleteGYBG_PMByWjm", wjm);
                operationLog = this.GetOperationLogItem(gybgPM, "DELETE", uname);
                if (null != operationLog)
                {
                    this.operationLogDAO.insertLogItem(operationLog);
                }

            }

            ICollection<GYBG_PM> list = this.GetSomeGYBG_PM(str[0], str[1], str[2], 1, 10000);

            int ph = 1;
            String phString = null;
            if (null != list)
            {
                foreach (GYBG_PM temp in list)
                {
                    phString = FormatPH(ph++);
                    //如果是目录则调过
                    if (temp.wjm.Equals(startWjm))
                    {
                        ph = 1;
                        continue;
                    }
                    //如果当前文件名与新文件名一样则不做处理
                    else if (temp.wjm.Equals(wjmStr + phString))
                    {
                        continue;
                    }
                    //如果当前文件名与新文件名不一致,则更新文件名及篇名信息
                    else
                    {
                        changeGYBGPMWjm(temp.wjm, wjmStr + phString);
                    }
                }
            }
            return result;
        }





        /// <summary>
        /// 按分类返回栏目信息
        /// </summary>
        /// <param name="fl">分类名</param>
        /// <returns></returns>
        public List<String> GetLMByFL(String fl)
        {
            List<String> list = new List<string>();

           
            bool flag = false;
            //GYBG_LM.xml文件路径
            String path =  System.AppDomain.CurrentDomain.BaseDirectory+ GlobalGYBG.GYBG_LM;
            path = path.Replace('\\', '/');

            try
            {
                StreamReader sr = new StreamReader(path, System.Text.Encoding.GetEncoding("UTF-8"));
                //StreamReader sr = new StreamReader(
                //创建XML文档操作对象
                XmlDocument xDoc = new XmlDocument();

                //加载文档信息
                xDoc.Load(sr);
                //获取根节点信息
                XmlNode xNode = xDoc.SelectSingleNode("GYBG");
                //获取子节点信息
                XmlNodeList children = xNode.ChildNodes;
                foreach (XmlNode temp in children)
                {
                    if (temp.Attributes["name"].Value.Equals(fl))
                    {
                        xNode = temp;
                        flag = true;
                        break;
                    }
                }

                if (flag)
                {
                    children = xNode.ChildNodes;
                    foreach (XmlNode temp in children)
                    {
                        list.Add(temp.InnerText);
                    }
                }
                sr.Close();
            }
            catch (Exception ex)
            {
                Console.Write(ex.ToString());
            }
            return list;
        }

        /// <summary>
        /// 根据索引编码、年份、期号获取最大文件的篇名信息
        /// </summary>
        /// <param name="flbm">分类编码</param>
        /// <param name="nf">年份</param>
        /// <param name="qh">期号</param>
        /// <returns></returns>
        public GYBG_PM getMaxGYBG_PM(String flbm, String nf, String qh)
        {
            if (null == flbm || "".Equals(flbm))
            {
                return null;
            }
            if (null == nf || "".Equals(nf))
            {
                return null;
            }
            if (null == qh || "".Equals(qh))
            {
                return null;
            }
            //设置匹配文件名
            String wjm = flbm + "-" + nf + "-" + qh + "%";
            return sqlMapper.QueryForObject<GYBG_PM>("SelectMaxGYBG_PM", wjm);
        }

        /// <summary>
        /// 生成日志信息
        /// </summary>
        /// <param name="zwqkPM">中文篇名信息</param>
        /// <param name="opType">操作类型</param>
        /// <param name="uname">用户名</param>
        /// <returns></returns>
        private OperationLogItem GetOperationLogItem(GYBG_PM gybgPM, String opType, String uname)
        {
            if (null == gybgPM)
            {
                return null;
            }

            OperationLogItem operationLogItem = new OperationLogItem();
            //操作类型
            operationLogItem.opType = opType;
            //数据库表
            operationLogItem.opTable = "GYBG_PM";
            //全文页数
            try
            {
                operationLogItem.opPageCount = Int32.Parse(gybgPM.ys);
            }
            catch (Exception)
            {
            }

            operationLogItem.opObjectID = "国研报告";
            // 操作涉及的书刊
            operationLogItem.opBookIn = "国研报告";

            // 时间
            operationLogItem.opDate = DateTime.Now;
            // 操作员
            operationLogItem.opPerson = uname;
            //记录操作模式，判断是否属于批量操作。取值范围SINGLE/BATCH。
            operationLogItem.opMode = "SINGLE";

            //操作的内容
            String content = "('" + gybgPM.flbm + "','" + gybgPM.sybm + "','" + gybgPM.wjm + "','" + gybgPM.dwjm + "','" + gybgPM.lm + "','" + gybgPM.bt + "','" + gybgPM.zzdw + "','" + gybgPM.zz + "','" + gybgPM.nf + "','" + gybgPM.bgrq + "','" + gybgPM.ztc + "','" + gybgPM.ly + "','" + gybgPM.wz + "','" + gybgPM.gxrq + "','" + gybgPM.ys + "')";
            operationLogItem.opContent = content;
            return operationLogItem;
        }


        /// <summary>
        /// 修改已有的文件名。
        /// </summary>
        /// <param name="oldWjm">旧文件名</param>
        /// <param name="newWjm">新文件名</param>
        /// <returns>是否修改成功</returns>
        public bool changeGYBGPMWjm(String oldWjm, String newWjm)
        {
            if (null == oldWjm || null == newWjm)
            {
                return false;
            }

            String dwjm = newWjm.Replace(".PDF", ".DOC");

            IDictionary<String, Object> para = new Dictionary<String, Object>();
            para.Add("oldwjm", oldWjm);
            para.Add("newwjm", newWjm);
            para.Add("dwjm", dwjm);

            bool result = true;
            try
            {
                sqlMapper.Update("ChangeGYBG_PM_wjm", para);
                //修改PDF文件名
                OperationFile.ReNameFile(oldWjm, newWjm);
                //修改DOC文件名
                oldWjm=oldWjm.Replace(".PDF", ".DOC");
                newWjm=newWjm.Replace(".PDF", ".DOC");
                OperationFile.ReNameFile(oldWjm, newWjm);

            }
            catch
            {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 规范篇号
        /// </summary>
        /// <param name="ph">篇号</param>
        /// <returns>4位篇号</returns>
        private String FormatPH(int ph)
        {
            String phString = ph.ToString();
            //长度为1
            if (phString.Length == 1)
            {
                phString = "000" + phString;
            }
            //长度为2
            else if (phString.Length == 2)
            {
                phString = "00" + phString;
            }
            else if (phString.Length == 3)
            {
                phString = "0" + phString;
            }
            return phString+".PDF";
        }

        public GYBG_DAO()
        {
            //
            // TODO: Add constructor logic here
            //
        }
    }
}